//
//  SetViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/3/27.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "SetViewController.h"
#import "MoreBlankTableViewHeaderFooterView.h"
#import "MyBusinessCardWXData.h"
#import "UpdatePwdViewController.h"
#import "SetPushMessageViewController.h"
#import "UserBindingPhoneViewController.h"

@interface SetViewController (){
    UITableView *tableViewUser;
    NSMutableArray *arrayAllData;
    
    NSDictionary *dicuserData;
}

@end

@implementation SetViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self refreshUserData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    arrayAllData=[NSMutableArray new];
//    [arrayAllData addObject:@[@{@"title":@"微信号"}]];
//    [arrayAllData addObject:@[@{@"title":@"手机号码"},@{@"title":@"修改密码"}]];
    [arrayAllData addObject:@[@{@"title":@"绑定手机"},@{@"title":@"修改密码"}]];//,@{@"title":@"推送设置"}
    
    if ([[[Utility Share] VersionSelect] floatValue]<[[[Utility Share] APPnewAppVersion] floatValue] && [[[Utility Share] APPpackPath] notEmptyOrNull]) {
        [arrayAllData addObject:@[@{@"title":@"当前版本"},@{@"title":@"更新提醒"},@{@"title":@"清除缓存"},@{@"title":@"一键清除红点"}]];
    }else{
        [arrayAllData addObject:@[@{@"title":@"当前版本"},@{@"title":@"清除缓存"},@{@"title":@"一键清除红点"}]];
    }
    [arrayAllData addObject:@[@{@"title":@"退出登录"}]];
    [arrayAllData addObject:@[]];
    
    
    tableViewUser=[[UITableView alloc]initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, kContentHeight)];
    //    [tableViewUser showRefresh:NO LoadMore:NO];
    tableViewUser.delegate = self;
    tableViewUser.dataSource = self;
    //    tableViewUser.delegate2=self;
    [tableViewUser setBackgroundColor:rgbGray];
    [tableViewUser setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [tableViewUser setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    [self.view addSubview:tableViewUser];
    [tableViewUser registerClass:[MoreBlankTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"MoreBlankTableViewHeaderFooterView"];
    
    
    
}

-(void)refreshUserData{
    //    XKFuser
//    [NetEngine createGetAction_LJ_two:[NSString stringWithFormat:XKFuser,[[Utility Share] userId],[[Utility Share] userToken]] onCompletion:^(id resData, BOOL isCache) {
//        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
//            dicuserData=[resData objectForJSONKey:@"data"];
//           
//            [tableViewUser reloadData];
//        }else{
//            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [super backButtonClicked:nil];
//            });
//        }
//    } onError:^(NSError *error) {
//        [SVProgressHUD showImage:nil status:alertErrorTxt];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [super backButtonClicked:nil];
//        });
//    }];
}


#pragma mark tableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [arrayAllData count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[arrayAllData objectAtIndex:section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic=[[arrayAllData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    NSString *identifier = dic.description.md5;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.backgroundColor=[UIColor clearColor];
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        
        UIView *BGV=[[UIView alloc]initWithFrame:cell.bounds];
        [BGV setBackgroundColor:RGBCOLOR(255, 255, 255)];
        [cell setBackgroundView: BGV];
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        if (![[dic valueForJSONStrKey:@"title"] isEqualToString:@"退出登录"]) {
            
            UILabel *lblName=[RHMethods labelWithFrame:CGRectMake(15, 12, 0, 20) font:fontTitle color:rgbTitleColor text:[dic valueForJSONStrKey:@"title"]];
            [cell addSubview:lblName];
            if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"当前版本"]){
                UILabel *lblV=[RHMethods labelWithFrame:CGRectMake(kScreenWidth-115, 12, 100, 20) font:fontTitle color:rgbTitleColor text:[[Utility Share] VersionSelectString]];
                [lblV setTextAlignment:NSTextAlignmentRight];
                [cell addSubview:lblV];
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            }else if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"更新提醒"]){
                UILabel *lblV=[RHMethods labelWithFrame:CGRectMake(kScreenWidth-130, 12, 100, 20) font:fontTitle color:rgbTxtGray text:@"有新版可用"];
                [lblV setTextAlignment:NSTextAlignmentRight];
                [cell addSubview:lblV];
                [cell addSubview:[RHMethods imageviewWithFrame:CGRectMake(kScreenWidth-22, (44-14)/2.0, 7, 14) defaultimage:@"redTip070116" contentMode:UIViewContentModeCenter]];
            }else if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"微信号"]){
                UILabel *lblContent=[RHMethods labelWithFrame:CGRectMake(100, 12, kScreenWidth-150, 0) font:fontTitle color:rgbTxtGray text:@"ads"];
                lblContent.tag=101;
                [cell addSubview:lblContent];
                UIImageView * userLogo=[RHMethods imageviewWithFrame:CGRectMake(kScreenWidth-45, 0, 20, 44) defaultimage:@"ewmIcon070116" contentMode:UIViewContentModeCenter];
                userLogo.userInteractionEnabled=NO;
                userLogo.tag=102;
                [cell addSubview:userLogo];
                
                [cell addSubview:[RHMethods imageviewWithFrame:CGRectMake(kScreenWidth-22, (44-14)/2.0, 7, 14) defaultimage:@"Righticon070116"]];
            }else if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"手机号码"]){
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                UILabel *lblV=[RHMethods labelWithFrame:CGRectMake(100, 12, 150, 20) font:fontTitle color:rgbTxtGray text:@""];
                lblV.tag=103;
                [cell addSubview:lblV];
            }else{
                [cell addSubview:[RHMethods imageviewWithFrame:CGRectMake(kScreenWidth-22, (44-14)/2.0, 7, 14) defaultimage:@"Righticon070116"]];
            }
            
            
        }else{
            
            UILabel *lblName=[RHMethods labelWithFrame:CGRectMake(15, 12, kScreenWidth-30, 20) font:fontTitle color:[UIColor redColor] text:@"退出登录"];
            [lblName setTextAlignment:NSTextAlignmentCenter];
            [cell addSubview:lblName];
        }
        [cell addSubview:[RHMethods imageviewWithFrame:CGRectMake(0, 43.5, kScreenWidth, 0.5) defaultimage:@"userLine"]];
    }
    if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"微信号"]){
        UIView *viewEwm=[cell viewWithTag:102];
        viewEwm.hidden=![[dicuserData valueForJSONStrKey:@"wxicon"] notEmptyOrNull];
        UILabel *lblContent=[cell viewWithTag:101];
        lblContent.text=[dicuserData valueForJSONStrKey:@"wechat"];
    }else if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"手机号码"]){
        UILabel *lblTel=[cell viewWithTag:103];
        lblTel.text=[dicuserData valueForJSONStrKey:@"mobile"];
    }
    
    
    return cell;
    
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic=[[arrayAllData objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"微信号"]) {
        if (dicuserData) {
            [self pushController:[MyBusinessCardWXData class] withInfo:@"" withTitle:@"微信号" withOther:dicuserData];
        }
    }else if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"修改密码"]) {
        [self pushController:[UpdatePwdViewController class] withInfo:@"" withTitle:@"修改密码" withOther:nil];
    }else if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"退出登录"]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"您将退出本次登录\n若退出登录，您的信息将从本手机移除" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag=111;
        [alert show];
    }else if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"更新提醒" ]){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[Utility Share] APPpackPath]]];
    }else if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"推送设置"]) {
        [self pushController:[SetPushMessageViewController class] withInfo:@"" withTitle:@"推送设置" withOther:nil];
    }else if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"清除缓存" ]){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"您确定要清理本地缓存信息？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag=110;
        [alert show];
    }else if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"绑定手机" ]){
        [self pushController:[UserBindingPhoneViewController class] withInfo:@"" withTitle:@"绑定手机" withOther:nil];
    }else if ([[dic valueForJSONStrKey:@"title"] isEqualToString:@"一键清除红点" ]){
      
        [QAlertView showAlertViewWithTitle:@"你确定要一键删除所有红点?" message:@"" cancelButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger index) {
           
            
            if (index == 1) {
                
                
                [self cancleRed];
                
                
            }
            
        }];
        
        
        
        
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 10.f;
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    MoreBlankTableViewHeaderFooterView *sectionView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MoreBlankTableViewHeaderFooterView"];
    return sectionView;
}

#pragma mark UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag==110 && buttonIndex==1) {
         [self clearCacheClicked];
    }else if (alertView.tag==111 && buttonIndex==1) {
        //取消所有的本地通知
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
        [[Utility Share] clearUserInfoInDefault];
        [[Utility Share] showLoginAlert:YES];
    }
}

-(void)clearCacheClicked{
    
    [SVProgressHUD showWithStatus:@"正在清理缓存" maskType:SVProgressHUDMaskTypeNone ];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSFileManager* fileManager=[NSFileManager defaultManager];
        NSString *_documentsDirectory = paths[0];
        NSString * cacheDirectoryName = [_documentsDirectory stringByAppendingPathComponent:MKNETWORKCACHE_DEFAULT_DIRECTORY];
        DLog(@"cacheDirectoryName:%@",cacheDirectoryName);
        
//        NSString *filespath = DOCUMENTS_CHAT_FOLDER;//语音文件
//        BOOL blDele= [fileManager removeItemAtPath:filespath error:nil];
//        DLog(@"语音删除:%d",blDele);
        
        
        NSArray * tempFileList = [[NSArray alloc] initWithArray:[fileManager contentsOfDirectoryAtPath:cacheDirectoryName error:nil]];
        for (NSString *strName in tempFileList) {
            NSString* fileAbsolutePath = [cacheDirectoryName stringByAppendingPathComponent:strName];
            
            BOOL blDele= [fileManager removeItemAtPath:fileAbsolutePath error:nil];
            DLog(@"删除:%d",blDele);
        }
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showImage:nil status:@"清理成功!"];
            
        });
    });
    
    
    
}
-(void)cancleRed{
    
    krequestParam
    [NetEngine createHttpAction:@"user/clearred" withCache:NO withParams:dictparam withMask:SVProgressHUDMaskTypeClear onCompletion:^(id resData, BOOL isCache) {
        [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            
            
            
            
            
        }else{
            
            
            
            
            
            
        }
        
    } onError:^(NSError *error) {
        
    }];
    
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
